//
//  ZZOAuthViewController.swift
//  web
//
//  Created by 张卓 on 2017/1/17.
//  Copyright © 2017年 ZZ. All rights reserved.
//

import UIKit
import YYModel

class ZZOAuthViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view = webVc
        setupUI()
        //设置URL
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")
        guard let u = url else {
            return
        }
        let res = URLRequest(url: u)
        //加载
        webVc.loadRequest(res)
    }
    //设置视图
    func setupUI() {
        setupNav()
    }
    
    //设置nav
    func setupNav() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: nil, title: "取消", target: self, action: #selector(cancelClick))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: nil, title: "自动填充", target: self, action: #selector(AutoClick))
    }
    
    
    //懒加载 webView
    fileprivate lazy var webVc:UIWebView = {
        let webview = UIWebView()
        //设置代理
        webview.delegate = self
        
        return webview
    }()
    
    
    
}
extension ZZOAuthViewController : UIWebViewDelegate {
    //开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        
    }
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
    }
    // webView 将要加载的请求  会走该方法,默认返回true 允许加载 将要加载的请求 默认如果不实现,该代理方法,默认都是允许加载
    //UIWebViewNavigationType
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //将要加载请求的字符串
        let urlString = request.url?.absoluteString
        //判断可选urlstring 是否为 nil   且字符串的前缀是回调页  前缀是hasPrefix
        if let u = urlString, u.hasPrefix(REDIRECT_URI) {
            
            //请求参数部分 url?.query从? 以后的部分
            let query = request.url?.query
            //判断请求参数query 是否为 nil
            if let q = query {
//                print(q)
                //截取code
                let code = q.substring(from: "code=".endIndex)
                print("终于等到你",code)
                //发送请求. 获取accessToken
//                getUserAccount(code: code)
//                let oauthViewMode = ZZOAuthViewModel()
                //已经拿到code
                ZZOAuthViewModel.shared.getUserAccount(code: code, isFinish: { (isFinish) in
                    if !isFinish {
                        print("失败")
                        return
                    }else {
                        print("成功")
//                        print(ZZOAuthViewModel.shared.userAccountModel)
                        //先要关闭当前控制器,然后发送通知
                        self.dismiss(animated: false, completion:{
                        //发送通知告知appdelegate 切换跟控制器
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue:SWITCHROOTVIEWCONTROLLERNOTI), object: nil)
                        })
                    }
                })
                return false
            }
            
        }
        
        return true
    }
    
}


//监听事件
extension ZZOAuthViewController {
    @objc fileprivate func cancelClick(){
        
        dismiss(animated: true, completion: nil)
    }
    @objc fileprivate func AutoClick() {
        print("自动填充是什么鬼")
        //JS字符串
        let jsString = "document.getElementById('userId').value='\(ZZWeiBoId)';document.getElementById('passwd').value='\(ZZPassWd)';"
        //JS注入
        webVc.stringByEvaluatingJavaScript(from: jsString)
        
    }
    
}
